package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper ;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //营业额统计业务返回数据 dataList turnoverList
        //营业额统计业务流程： 根据日期范围先往日期集合填充数据
        //然后根据日期范围查询营业额数据，填充到营业额集合中
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        //循环往日期集合中填充数据
        while(!begin.equals(end))
        {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        //填充营业额数据
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //localTime.MIN代表每天的0:0:0
            LocalDateTime begintime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map mp = new HashMap();
            mp.put("status", Orders.COMPLETED);
            mp.put("begin",begintime);
            mp.put("end",endtime);
            Double turnover = reportMapper.stasticByMap(mp);
            turnover = turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }
        return  TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> newUserList = new ArrayList<>(); //新增用户数
        List<Integer> totalUserList = new ArrayList<>(); //总用户数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //新增用户数量 select count(id) from user where create_time > ? and create_time < ?
            Integer newUser = getUserCount(beginTime, endTime);
            //总用户数量 select count(id) from user where  create_time < ?
            Integer totalUser = getUserCount(null, endTime);

            newUserList.add(newUser);
            totalUserList.add(totalUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }
    /**
     * 根据时间区间统计用户数量
     * @param beginTime
     * @param endTime
     * @return
     */
    private Integer getUserCount(LocalDateTime beginTime, LocalDateTime endTime) {
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end", endTime);
        return userMapper.countByMap(map);
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO orderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Integer> orderCountList = new ArrayList<>(); // 每日订单数
        List<Integer> validOrderCountList = new ArrayList<>(); // 每日有效订单数
        Integer totalOrderCount = 0; // 订单总数
        Integer validOrderCount = 0; // 有效订单数

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            
            // 查询每日订单总数
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);
            Integer dailyOrderCount = reportMapper.countByMap(map);
            orderCountList.add(dailyOrderCount);
            totalOrderCount += dailyOrderCount;
            
            // 查询每日有效订单数（状态为已完成）
            map.put("status", Orders.COMPLETED);
            Integer dailyValidOrderCount = reportMapper.countByMap(map);
            validOrderCountList.add(dailyValidOrderCount);
            validOrderCount += dailyValidOrderCount;
        }
        
        // 计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量TOP10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO salesTop10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        
        List<GoodsSalesDTO> salesTop10 = reportMapper.getSalesTop10(beginTime, endTime);
        
        List<String> nameList = new ArrayList<>();
        List<String> numberList = new ArrayList<>();
        
        for (GoodsSalesDTO goodsSales : salesTop10) {
            nameList.add(goodsSales.getName());
            numberList.add(goodsSales.getNumber().toString());
        }
        
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }
    /**导出近30天的运营数据报表
     * @param response
     **/
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        
        try {
            //创建新的Excel工作簿
            XSSFWorkbook excel = new XSSFWorkbook();
            //创建Sheet页
            XSSFSheet sheet = excel.createSheet("运营数据报表");
            
            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment;filename=运营数据报表_" + begin + "_" + end + ".xlsx");
            
            //创建标题行
            XSSFRow titleRow = sheet.createRow(0);
            titleRow.createCell(0).setCellValue("运营数据报表 (" + begin + " 至 " + end + ")");
            
            //创建表头行
            XSSFRow headerRow = sheet.createRow(2);
            headerRow.createCell(0).setCellValue("日期");
            headerRow.createCell(1).setCellValue("营业额");
            headerRow.createCell(2).setCellValue("有效订单数");
            headerRow.createCell(3).setCellValue("订单完成率");
            headerRow.createCell(4).setCellValue("平均单价");
            headerRow.createCell(5).setCellValue("新增用户数");
            
            //填充数据
            int rowNum = 3;
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询每日数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                
                XSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(date.toString());
                row.createCell(1).setCellValue(businessData.getTurnover() != null ? businessData.getTurnover() : 0.0);
                row.createCell(2).setCellValue(businessData.getValidOrderCount() != null ? businessData.getValidOrderCount() : 0);
                row.createCell(3).setCellValue(businessData.getOrderCompletionRate() != null ? businessData.getOrderCompletionRate() : 0.0);
                row.createCell(4).setCellValue(businessData.getUnitPrice() != null ? businessData.getUnitPrice() : 0.0);
                row.createCell(5).setCellValue(businessData.getNewUsers() != null ? businessData.getNewUsers() : 0);
            }
            
            //自动调整列宽
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }
            
            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();

        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
